package com.wink_172.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.wink_172.adapter.HBomeListAdapter
import com.wink_172.commons.R
import com.wink_172.commons.databinding.ActivityAppListBinding
import com.wink_172.library.AppManager
import com.wink_172.library.activity.DownAppActivity
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.adapter.HomeListAdapter
import com.wink_172.library.model.BaseDataItem
import com.wink_172.library.model.Constants
import com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE_PERMISSION
import com.wink_172.library.model.Constants.TENCENT_BUCKET_OFFICE_URL
import com.wink_172.library.model.Constants.TENCENT_OSS_PACKAGE_NAME_temp_fd
import com.wink_172.library.model.json.FileData
import com.wink_172.library.utils.CommonUtils
import com.wink_172.library.utils.FileUtil
import com.wink_172.library.view.ActionBarView
import com.wink_172.library.view.CustomRecyclerView
import org.xutils.x
import java.util.*
import kotlin.collections.ArrayList

/**
 * 所有app更新地址
 * 所有特殊文件更新地址
 *
 *
 * */
class DownListActivity : SmartActivity() {
    lateinit  var binding: ActivityAppListBinding

    companion object {
        @JvmStatic
        fun startActivity(context: Context, vararg args: Any?) {
            val intent = Intent(context, DownListActivity::class.java)

            //intent.putExtra(Constants.PARAM_DATA1, (String) args[0]);
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_app_list)

        setStatusBarLightMode()
        initView()
        init()
    }


    fun init() {
        val list_data: MutableList<FileData>? = ArrayList();

        val fileData = FileData()
        fileData.web_url =
            "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/sync_fd/"
        fileData.name = "sync_fd文件夹同步（下载）"
        list_data!!.add(fileData)

        val fileData1 = FileData()
        fileData1.web_url =
            "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/dance-release.apk"
        fileData1.name = "天天跳舞正式版(测试域名)替换安装"
        list_data!!.add(fileData1)

        val fileData2 = FileData()
        fileData2.web_url =
            "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/dance-debug.apk"
        fileData2.name = "天天跳舞测试替换安装"
        list_data!!.add(fileData2)

        val fileData5 = FileData()
        fileData5.web_url =
            "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/wink-172-debug.apk"
        fileData5.name = "wink172-utils替换安装"
        list_data!!.add(fileData5)




        if (Constants.SUPER_UER) {
            val fileData3 = FileData()
            fileData3.web_url =
                "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/small-link-debug.apk"
            fileData3.name = "短视频精选替换安装"
            list_data!!.add(fileData3)


        }


        for (i in 0..10000 - 1) {
            val fileData5 = FileData()
            fileData5.web_url =
                "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/wink-172-debug.apk"
            fileData5.name = ""+UUID.randomUUID()
            list_data!!.add(fileData5)
        }
        initList(list_data)


    }

    private fun initView() {
        (binding!!.actionBar as ActionBarView).updateAllContent(
            com.wink_172.library.R.mipmap.icon_back,
            "文件下载列表",
            ""
        );
        (binding!!.actionBar as ActionBarView).setCallback(object : ActionBarView.ICallback {
            override fun onSendEvent(event: Int, content: String?) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish()
                }
            }
        })


        val list: List<Any?> = ArrayList()
        val homeListAdapter = HBomeListAdapter(this, list, binding!!.listView)
        binding!!.listView.init(homeListAdapter, false)
        val layoutManager = LinearLayoutManager(binding!!.root.context)
        binding!!.listView.layoutManager = layoutManager


        binding!!.listView.setCallback(object : CustomRecyclerView.ICallback {
            override fun onLoadMore() {

            }
        })
    }

    /**
     * 特殊的腾讯云文件夹下载事件
     * 因为无法直接获取到腾讯云目录下的文件，只能手动添加
     * */
    fun specDownFd(fileData: FileData) {
        val list: MutableList<String>? = ArrayList();

        list!!.add(fileData.web_url + "1.txt")


        for (i in 0..list!!.size - 1) {
            val web_url = list.get(i)
            val save_path = Constants.savePath + FileUtil.getFileUrlName(web_url) //本地保存绝对路径
            CommonUtils.downLoadFile(list.get(i), save_path,
                object :
                    com.wink_172.library.callback.ICallback {
                    override fun onSendEvent(event: Int, vararg args: Any?) {//这个callback用的非常巧妙

                        when (event) {
                            Constants.EventEnum.网络请求成功.ordinal -> {
                                CommonUtils.showToast(FileUtil.getFileUrlName(web_url) + "下载成功")
                            }
                            Constants.EventEnum.网络请求错误.ordinal -> {
                                CommonUtils.showToast(FileUtil.getFileUrlName(web_url) + "下载失败")
                            }

                        }
                    }
                }
            )

        }
    }

    private val PERMISSIONS = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
    )

    /**
     *
     * * */
    fun initList(list_data: MutableList<FileData>) {
        val list: MutableList<Any> = ArrayList()
        for (i in 0..list_data.size - 1) {
            val baseDataItem = BaseDataItem(i, com.wink_172.model.Constants.SCENE_DOWN_LOAD_LIST)

            val info12 = list_data.get(i) as FileData
            baseDataItem.setObjectData(info12)
            baseDataItem.callback = object : HomeListAdapter.BaseViewsHolder.ICallback {
                override fun postObject(event: Int, vararg args: Any?) {
                    when (event) {
                        Constants.EVENT_01 -> {

                            if (!checkPermissions(PERMISSIONS)) {
                                requestPermissions(ACTIVITY_REQUEST_CODE_PERMISSION, PERMISSIONS)
                            } else {

                                if (i == 0) {
                                    specDownFd(info12)

                                } else
                                    if (info12.web_url.contains("apk")) {
                                        DownAppActivity.startActivity(
                                           activity,
                                            info12.web_url,
                                            "data/data/"+ x.app().packageName+"/wink-172-cache/" + FileUtil.getFileUrlName(
                                                info12.web_url
                                            )
                                        )  //下载并安装
                                    }
                            }

                        }
                    }
                }
            }
            list.add(baseDataItem)
        }

        val homeListAdapter = binding!!.listView.adapter as HBomeListAdapter?
        if (binding!!.swipeRefreshView.isRefreshing) {

            binding!!.listView.currentPage = 1
            homeListAdapter!!.swapContent(list)
            homeListAdapter.notifyDataSetChanged()
        } else if (list.size > 0) {
            binding!!.listView.currentPage = (binding!!.listView.currentPage + 1)
            homeListAdapter!!.appendContent(list, false)
            homeListAdapter.notifyDataSetChanged()
        }
        binding!!.swipeRefreshView.isRefreshing = false
        binding!!.listView.isLoadingMore = false
    }
}